package belpic.spring_data.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import belpic.spring_data.domain.User;
import belpic.spring_data.repository.UserRepository;

@Controller
@RequestMapping("/users")
public class UsersController {

	@Autowired
	private UserRepository repository;
	
	@RequestMapping(value="/{id}", method=RequestMethod.GET)
	public ModelAndView showUserForm(@PathVariable Long id){
		ModelAndView mav = new ModelAndView("user");
		User user = repository.findOne(id);
		mav.addObject("user", user);
		return mav;
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView showForm(){
		ModelAndView mav = new ModelAndView("userForm");
		mav.addObject("command", new User());
		return mav;
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String saveUser(@ModelAttribute("command") @Valid User user, BindingResult binder){
		
		if(binder.hasErrors()){
			System.out.println(binder.getAllErrors());
			return "userForm";
		}
		
		repository.save(user);
		return "redirect:/users/" + user.getId();
	}
	
}
